package com.itheima.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
@Component
public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {
    public static final String PARAM_NAME="param";
    //构造方法
    public MyParamGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(PARAM_NAME);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();//获取request
            //判断请求中是否有需要的参数
            if (request.getQueryParams().containsKey(config.param)){
                //获取参数的值
              request.getQueryParams().get(config.param).forEach(value -> System.out.printf("----------局部过滤器-----%s = %s-----",config.param,value));
            }
            return chain.filter(exchange);
        };
    }


    public static class Config {
        //和配置文件中过滤器配置的参数名称一样
        private String param;

        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }
    }
}
